// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using SnapObjects.Commons;

namespace SnapObjects.Data
{
    public static class AdoDbParameterBuilder
    {
        public static void AddDbParameter(
            [NotNull] DbCommand command,
            [NotNull] IAdoDbParameter adoDbParameter)
        {
            Check.NotNull(command, nameof(command));
            Check.NotNull(adoDbParameter, nameof(adoDbParameter));
            
            IDbDataParameter dataParameter = command.CreateParameter();
            dataParameter.ParameterName = adoDbParameter.ParameterName;
            
            dataParameter.Direction = adoDbParameter.Direction;
            
            if (adoDbParameter.Value == null)
            {
                dataParameter.Value = DBNull.Value;
            }
            else
            {
                dataParameter.Value = adoDbParameter.Value;
            }
            
            command.Parameters.Add(dataParameter);
        }
        
        public static void AddDbParameter(
            [NotNull] DbCommand command,
            [NotNull] TypeMapping typeMapping,
            [NotNull] IAdoDbParameter adoDbParameter)
        {
            Check.NotNull(command, nameof(command));
            Check.NotNull(typeMapping, nameof(typeMapping));
            Check.NotNull(adoDbParameter, nameof(adoDbParameter));
            
            var parameter = typeMapping.CreateParameter(command, adoDbParameter);
                
            command.Parameters.Add(parameter);
        }
    }
}
